[id].vue 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. <template>
  2. <div class="admin--page-content">
  3. <div class="admin--form">
  4. <form @submit.prevent="handleSubmit">
  5. <!-- ============================
  6. 챌린지 기본 정보
  7. ============================ -->
  8. <table class="admin--form--table">
  9. <colgroup>
  10. <col style="width: 140px;">
  11. <col>
  12. </colgroup>
  13. <tbody>
  14. <tr>
  15. <th><div>챌린지명 <span class="admin--required">*</span></div></th>
  16. <td>
  17. <div class="input--wrap">
  18. <input v-model="formData.name" type="text" class="w--full admin--form-input" placeholder="예: 동해안 왕대구 선상낚시대회" required />
  19. </div>
  20. </td>
  21. </tr>
  22. <tr>
  23. <th><div>참가비 <span class="admin--required">*</span></div></th>
  24. <td>
  25. <div class="input--wrap">
  26. <input
  27. v-model="formData.fee"
  28. type="number"
  29. min="0"
  30. class="admin--form-input w--200"
  31. :placeholder="isFree ? '0 (무료)' : '예: 10000'"
  32. :disabled="isFree"
  33. required
  34. />
  35. <span>원</span>
  36. <label class="admin--radio-label ml--16">
  37. <input type="checkbox" v-model="isFree" @change="onFreeChange" /> 무료
  38. </label>
  39. </div>
  40. </td>
  41. </tr>
  42. <tr>
  43. <th><div>기간 <span class="admin--required">*</span></div></th>
  44. <td>
  45. <div class="input--wrap">
  46. <DatePicker v-model="startDate" placeholder="📅 YYYY-MM-DD" />
  47. <span class="admin--date-separator">-</span>
  48. <DatePicker v-model="endDate" placeholder="📅 YYYY-MM-DD" />
  49. </div>
  50. </td>
  51. </tr>
  52. <tr>
  53. <th><div>최대 참가자 <span class="admin--required">*</span></div></th>
  54. <td>
  55. <div class="input--wrap">
  56. <input v-model="formData.max_participants" type="number" min="100" max="999999" class="admin--form-input w--120" placeholder="100 ~ 999999" required />
  57. <span>명</span>
  58. </div>
  59. </td>
  60. </tr>
  61. <tr>
  62. <th><div>타이틀 이미지</div></th>
  63. <td>
  64. <div class="input--wrap">
  65. <input
  66. ref="imageInput"
  67. type="file"
  68. accept="image/*"
  69. class="admin--form-file-hidden"
  70. @change="onImageChange"
  71. />
  72. <button type="button" class="admin--btn-small admin--btn-blue" @click="triggerImageInput">
  73. {{ existingImagePath || image ? '이미지 변경' : '이미지 선택' }}
  74. </button>
  75. <span v-if="image" class="ml--16">{{ image.file.name }} (신규)</span>
  76. <span v-else-if="existingImagePath" class="ml--16">{{ existingImageName || '기존 이미지' }}</span>
  77. <button
  78. v-if="existingImagePath && !image"
  79. type="button"
  80. class="admin--btn-small admin--btn-red ml--8"
  81. @click="removeExistingImage"
  82. >
  83. 이미지 제거
  84. </button>
  85. </div>
  86. <p class="mt--10">권장 1200x800, JPG/PNG/GIF/WebP, 5MB 이하 (선택 사항)</p>
  87. <!-- 신규 이미지 미리보기 (있으면 우선) -->
  88. <div v-if="image" class="onboard--photo-grid mt--10">
  89. <div class="onboard--photo-item">
  90. <img :src="image.preview" alt="신규 미리보기" />
  91. <button type="button" class="onboard--photo-remove" @click="removeImage"></button>
  92. </div>
  93. </div>
  94. <!-- 신규 없으면 기존 이미지 -->
  95. <div v-else-if="existingImagePath" class="onboard--photo-grid mt--10">
  96. <div class="onboard--photo-item">
  97. <img :src="getImageUrl(existingImagePath)" alt="기존 이미지" />
  98. </div>
  99. </div>
  100. </td>
  101. </tr>
  102. <tr>
  103. <th><div>상태 <span class="admin--required">*</span></div></th>
  104. <td>
  105. <div class="input--wrap">
  106. <label class="admin--radio-label">
  107. <input type="radio" v-model="formData.status_YN" value="Y" /> 사용중
  108. </label>
  109. <label class="admin--radio-label ml--16">
  110. <input type="radio" v-model="formData.status_YN" value="N" /> 미사용
  111. </label>
  112. </div>
  113. </td>
  114. </tr>
  115. <tr>
  116. <th><div>상세내용</div></th>
  117. <td>
  118. <ClientOnly>
  119. <SunEditor
  120. v-model="formData.description"
  121. height="400px"
  122. placeholder="챌린지 상세 설명을 입력하세요. (참가 방법ㆍ규칙ㆍ유의사항 등)"
  123. />
  124. </ClientOnly>
  125. </td>
  126. </tr>
  127. </tbody>
  128. </table>
  129. <!-- ============================
  130. 라운드 설정
  131. ============================ -->
  132. <h3 class="admin--table--middle--title">라운드 설정</h3>
  133. <p class="admin--table--middle--desc">
  134. 라운드별로 장소 범위(전체/개별)를 선택하고, 장소마다 아이템을 배정합니다. 최대 5라운드까지 등록할 수 있습니다.
  135. </p>
  136. <div
  137. v-for="(round, rIdx) in rounds"
  138. :key="round._key"
  139. class="admin--round--box--wrap"
  140. :class="{ 'mt--16': rIdx > 0 }"
  141. >
  142. <div class="admin--round--title">
  143. 라운드 {{ round.round_no }}
  144. <span v-if="round.place_mode === 'all'">전체 장소ㆍ아이템 {{ round.items.length }}</span>
  145. <span v-else>개별 장소 {{ round.places.length }}</span>
  146. <!-- 최소 2라운드 이상. 3라운드부터 라운드 삭제 버튼 노출 -->
  147. <button
  148. v-if="rounds.length > 2"
  149. type="button"
  150. class="round--remove--btn"
  151. @click="removeRound(rIdx)"
  152. >
  153. 라운드 삭제
  154. </button>
  155. </div>
  156. <div class="admin--round--box">
  157. <div class="input--wrap mt--16">
  158. <label class="admin--round--radio">
  159. <input
  160. type="radio"
  161. :name="'place_mode_' + round._key"
  162. value="all"
  163. :checked="round.place_mode === 'all'"
  164. @change="changePlaceMode(round, 'all')"
  165. />
  166. 전체 장소에 동일 적용
  167. </label>
  168. <label class="admin--round--radio">
  169. <input
  170. type="radio"
  171. :name="'place_mode_' + round._key"
  172. value="specific"
  173. :checked="round.place_mode === 'specific'"
  174. @change="changePlaceMode(round, 'specific')"
  175. />
  176. 장소별 개별 설정
  177. </label>
  178. </div>
  179. <div class="qual--wrap">
  180. <p class="mt--16 mb--4">진출자 {{ rIdx === 0 ? '인원' : '확률' }}</p>
  181. <div class="input--wrap">
  182. <input
  183. v-model="round.qualified"
  184. type="number"
  185. min="1"
  186. class="admin--form-input w--120"
  187. :placeholder="rIdx === 0 ? '예: 30' : '예: 50'"
  188. required
  189. />
  190. <!-- 1라운드 단위 : 명, 그 외 라운드 단위 : % -->
  191. <span>{{ rIdx === 0 ? '명' : '%' }}</span>
  192. </div>
  193. </div>
  194. <!-- 전체 적용 모드 — 라운드 단위 아이템 -->
  195. <div v-if="round.place_mode === 'all'" class="item--select--wrap">
  196. <div class="item--select--btn--wrap mt--16 mb--4">
  197. <p>배정 아이템ㆍ수량 {{ round.items.length }}</p>
  198. <button type="button" @click="openItemModal(round)">+ 아이템 선택</button>
  199. </div>
  200. <div class="item--selected--wrap">
  201. <div v-for="(it, iIdx) in round.items" :key="it.item_id" class="item--selected">
  202. {{ it.name }}<button type="button" @click="round.items.splice(iIdx, 1)">✕</button>
  203. </div>
  204. </div>
  205. </div>
  206. <!-- 장소별 개별 설정 모드 -->
  207. <template v-else>
  208. <div
  209. v-for="(place, pIdx) in round.places"
  210. :key="place._key"
  211. class="round--place--wrap"
  212. >
  213. <div class="admin--round--title">
  214. 장소 {{ pIdx + 1 }}
  215. <button
  216. type="button"
  217. class="place--remove--btn"
  218. @click="removePlace(round, pIdx)"
  219. >✕</button>
  220. </div>
  221. <div class="place--select--wrap">
  222. <p class="mb--4">장소 정의</p>
  223. <!-- 분야/지역/제휴 셀렉트 — 항상 노출 -->
  224. <div class="input--wrap">
  225. <select v-model="place.field_id" class="admin--form-select">
  226. <option value="">전체 분야</option>
  227. <option v-for="f in fieldOptions" :key="f.id" :value="f.id">{{ f.name }}</option>
  228. </select>
  229. <select v-model="place.area_id" class="admin--form-select">
  230. <option value="">전체 지역</option>
  231. <option v-for="a in areaOptions" :key="a.id" :value="a.id">{{ a.name }}</option>
  232. </select>
  233. <select v-model="place.partnership_YN" class="admin--form-select">
  234. <option value="">제휴 여부</option>
  235. <option value="Y">제휴</option>
  236. <option value="N">비제휴</option>
  237. </select>
  238. <!-- 장소 미선택 시: "장소 선택" 버튼 + 드롭다운 -->
  239. <div v-if="place.onboards.length === 0" class="place--select--btn--wrap">
  240. <button
  241. type="button"
  242. class="admin--form-select"
  243. @click.stop="openDropdown(place)"
  244. >
  245. 장소 선택
  246. </button>
  247. <div
  248. v-if="place.dropdownOpen"
  249. class="all--place--wrap"
  250. @click.stop
  251. >
  252. <div class="place--top">
  253. <div class="search--wrap">
  254. <input v-model="place.searchKeyword" type="text" placeholder="선상ㆍ낚시터명 검색">
  255. </div>
  256. <div class="check--wrap">
  257. <label>
  258. <input
  259. type="checkbox"
  260. :checked="isAllFilteredSelected(place)"
  261. @change="toggleAll(place)"
  262. >
  263. 전체
  264. <span>조건의 모든 장소에 적용</span>
  265. </label>
  266. </div>
  267. <div class="all--place">
  268. <p>등록된 선상ㆍ낚시터</p>
  269. <ul class="all--place--list mt--6">
  270. <template v-for="group in groupedFilteredPlaces(place)" :key="group.area">
  271. <p class="group--header">
  272. {{ group.area }}
  273. <button
  274. type="button"
  275. @click="toggleAllInGroup(place, group.items)"
  276. >
  277. {{ isAllInGroupSelected(place, group.items) ? '그룹 해제' : '그룹 전체 선택' }}
  278. </button>
  279. </p>
  280. <li v-for="p in group.items" :key="placeKey(p)">
  281. <label>
  282. <input
  283. type="checkbox"
  284. :checked="place.tempSelected.includes(placeKey(p))"
  285. @change="togglePlaceInTemp(place, placeKey(p))"
  286. >
  287. <span>{{ p._placeType === 'onboard' ? '🚤' : '🎣' }} {{ p.name }}</span>
  288. <span :class="p.partnership_YN === 'Y' ? 'on' : 'off'">
  289. {{ p.partnership_YN === 'Y' ? '제휴' : '비제휴' }}
  290. </span>
  291. <p>{{ p.field_name || '-' }}</p>
  292. </label>
  293. </li>
  294. </template>
  295. <li v-if="filteredPlaces(place).length === 0" class="empty">
  296. 조건에 맞는 장소가 없습니다.
  297. </li>
  298. </ul>
  299. </div>
  300. </div>
  301. <div class="place--bot">
  302. <p>{{ place.tempSelected.length }}개 선택</p>
  303. <button type="button" @click="applyDropdown(place)">적용</button>
  304. </div>
  305. </div>
  306. </div>
  307. </div>
  308. <!-- 장소 선택 후 — 별도 영역에 "선상ㆍ낚시터 복수 선택" + 칩 -->
  309. <template v-if="place.onboards.length > 0">
  310. <p class="mt--16 mb--4">선상ㆍ낚시터 복수 선택</p>
  311. <div class="place--select--btn--wrap">
  312. <div
  313. class="admin--form-select"
  314. @click.stop="openDropdown(place)"
  315. >
  316. <div
  317. v-for="key in place.onboards.slice(0, 2)"
  318. :key="key"
  319. class="place--selected"
  320. >
  321. {{ placeTypeByKey(key) === 'onboard' ? '🚤' : '🎣' }} {{ placeNameByKey(key) }}
  322. <button
  323. type="button"
  324. @click.stop="removePlaceChip(place, key)"
  325. >✕</button>
  326. </div>
  327. <div v-if="place.onboards.length > 2" class="place--selected">
  328. + {{ place.onboards.length - 2 }}
  329. </div>
  330. </div>
  331. <div
  332. v-if="place.dropdownOpen"
  333. class="all--place--wrap"
  334. @click.stop
  335. >
  336. <div class="place--top">
  337. <div class="search--wrap">
  338. <input v-model="place.searchKeyword" type="text" placeholder="선상ㆍ낚시터명 검색">
  339. </div>
  340. <div class="check--wrap">
  341. <label>
  342. <input
  343. type="checkbox"
  344. :checked="isAllFilteredSelected(place)"
  345. @change="toggleAll(place)"
  346. >
  347. 전체
  348. <span>조건의 모든 장소에 적용</span>
  349. </label>
  350. </div>
  351. <div class="all--place">
  352. <p>등록된 선상ㆍ낚시터</p>
  353. <ul class="all--place--list mt--6">
  354. <template v-for="group in groupedFilteredPlaces(place)" :key="group.area">
  355. <p class="group--header">
  356. {{ group.area }}
  357. <button
  358. type="button"
  359. @click="toggleAllInGroup(place, group.items)"
  360. >
  361. {{ isAllInGroupSelected(place, group.items) ? '그룹 해제' : '그룹 전체 선택' }}
  362. </button>
  363. </p>
  364. <li v-for="p in group.items" :key="placeKey(p)">
  365. <label>
  366. <input
  367. type="checkbox"
  368. :checked="place.tempSelected.includes(placeKey(p))"
  369. @change="togglePlaceInTemp(place, placeKey(p))"
  370. >
  371. <span>{{ p._placeType === 'onboard' ? '🚤' : '🎣' }} {{ p.name }}</span>
  372. <span :class="p.partnership_YN === 'Y' ? 'on' : 'off'">
  373. {{ p.partnership_YN === 'Y' ? '제휴' : '비제휴' }}
  374. </span>
  375. <p>{{ p.field_name || '-' }}</p>
  376. </label>
  377. </li>
  378. </template>
  379. <li v-if="filteredPlaces(place).length === 0" class="empty">
  380. 조건에 맞는 장소가 없습니다.
  381. </li>
  382. </ul>
  383. </div>
  384. </div>
  385. <div class="place--bot">
  386. <p>{{ place.tempSelected.length }}개 선택</p>
  387. <button type="button" @click="applyDropdown(place)">적용</button>
  388. </div>
  389. </div>
  390. </div>
  391. </template>
  392. </div>
  393. <!-- 장소별 아이템 -->
  394. <div class="item--select--wrap">
  395. <div class="item--select--btn--wrap mb--4 mt--16">
  396. <p>배정 아이템ㆍ수량 {{ place.items.length }}</p>
  397. <button type="button" @click="openItemModal(place)">+ 아이템 선택</button>
  398. </div>
  399. <div class="item--selected--wrap">
  400. <div v-for="(it, iIdx) in place.items" :key="it.item_id" class="item--selected">
  401. {{ it.name }}<button type="button" @click="place.items.splice(iIdx, 1)">✕</button>
  402. </div>
  403. </div>
  404. </div>
  405. </div>
  406. <button type="button" class="place--add--btn" @click="addPlace(round)">
  407. + 장소 추가
  408. </button>
  409. </template>
  410. </div>
  411. </div>
  412. <button
  413. v-if="rounds.length < 5"
  414. type="button"
  415. class="round--add--btn"
  416. @click="addRound"
  417. >
  418. + 라운드 추가 (최대 5라운드)
  419. </button>
  420. <!-- 버튼 영역 -->
  421. <div class="admin--form-actions">
  422. <button type="button" class="admin--btn" @click="goToDetail">
  423. ← 취소
  424. </button>
  425. <button type="submit" class="admin--btn admin--btn-red ml--auto" :disabled="isSaving || isLoading">
  426. {{ isSaving ? "저장 중..." : "수정 저장" }}
  427. </button>
  428. </div>
  429. <!-- 성공/에러 메시지 -->
  430. <div v-if="successMessage" class="admin--alert admin--alert-success">
  431. {{ successMessage }}
  432. </div>
  433. <div v-if="errorMessage" class="admin--alert admin--alert-error">
  434. {{ errorMessage }}
  435. </div>
  436. </form>
  437. </div>
  438. <!-- ============================
  439. 아이템 선택 모달
  440. ============================ -->
  441. <ClientOnly>
  442. <Teleport to="body">
  443. <div
  444. v-if="itemModal.isOpen"
  445. class="admin--modal-overlay admin--alert-overlay"
  446. @click.self="closeItemModal"
  447. >
  448. <div class="admin--modal admin--form-modal admin--item-modal" @click.stop>
  449. <div class="admin--modal-header">
  450. <h4>아이템 선택</h4>
  451. <button type="button" class="admin--modal-close" @click="closeItemModal">✕</button>
  452. </div>
  453. <div class="admin--modal-body">
  454. <div class="admin--item-modal__search mb--16">
  455. <input
  456. v-model="itemModal.searchKeyword"
  457. type="text"
  458. class="admin--form-input w--full"
  459. placeholder="🔍 아이템명 검색"
  460. />
  461. </div>
  462. <ul v-if="filteredItems().length > 0" class="admin--item-modal__grid">
  463. <li
  464. v-for="it in filteredItems()"
  465. :key="it.id"
  466. class="admin--item-modal__card"
  467. :class="{ 'is-selected': itemModal.tempSelected.includes(it.id) }"
  468. >
  469. <label>
  470. <input
  471. type="checkbox"
  472. :checked="itemModal.tempSelected.includes(it.id)"
  473. @change="toggleItemInModal(it.id)"
  474. />
  475. <div class="admin--item-modal__thumb">
  476. <img
  477. v-if="it.file_path"
  478. :src="getImageUrl(it.file_path)"
  479. :alt="it.name"
  480. />
  481. <div v-else class="admin--item-modal__no-img">🎁</div>
  482. </div>
  483. <div class="admin--item-modal__name">{{ it.name }}</div>
  484. <div class="admin--item-modal__meta">
  485. <span v-if="it.type" class="admin--item-modal__type">{{ it.type == 'B' ? '뱃지' : it.type == 'P' ? '포인트' : '진출권' }}</span>
  486. <span v-if="it.point !== null && it.point !== undefined" class="admin--item-modal__point">{{ it.point }}P</span>
  487. </div>
  488. </label>
  489. </li>
  490. </ul>
  491. <div v-else class="admin--item-modal__empty">
  492. {{ itemModal.searchKeyword ? '검색 결과가 없습니다.' : '등록된 아이템이 없습니다.' }}
  493. </div>
  494. </div>
  495. <div class="admin--modal-footer">
  496. <span class="admin--item-modal__count mr--auto">{{ itemModal.tempSelected.length }}개 선택</span>
  497. <button type="button" class="admin--btn" @click="closeItemModal">취소</button>
  498. <button type="button" class="admin--btn admin--btn-primary-fill ml--8" @click="applyItemModal">적용</button>
  499. </div>
  500. </div>
  501. </div>
  502. </Teleport>
  503. </ClientOnly>
  504. </div>
  505. </template>
  506. <script setup>
  507. import { ref, onMounted, onBeforeUnmount } from "vue";
  508. import { useRoute, useRouter } from "vue-router";
  509. import DatePicker from "~/components/admin/DatePicker.vue";
  510. import SunEditor from "~/components/admin/SunEditor.vue";
  511. definePageMeta({
  512. layout: "admin",
  513. middleware: ["auth"],
  514. });
  515. const route = useRoute();
  516. const router = useRouter();
  517. const { get, put, del, upload } = useApi();
  518. const { getImageUrl } = useImage();
  519. const challengeId = Number(route.params.id);
  520. const isLoading = ref(false);
  521. const isSaving = ref(false);
  522. const successMessage = ref("");
  523. const errorMessage = ref("");
  524. // ============================
  525. // 옵션 데이터
  526. // ============================
  527. const fieldOptions = ref([]);
  528. const areaOptions = ref([]);
  529. const placesAll = ref([]); // 검색용 전체 장소 (선상 + 낚시터, _placeType 필드로 구분)
  530. const itemsAll = ref([]); // 아이템 모달용 전체 아이템
  531. // ============================
  532. // 챌린지 기본 정보
  533. // ============================
  534. const formData = ref({
  535. name: "",
  536. fee: "",
  537. max_participants: "",
  538. status_YN: "Y",
  539. description: "",
  540. });
  541. const startDate = ref("");
  542. const endDate = ref("");
  543. const isFree = ref(false);
  544. // 무료 체크박스 토글
  545. const onFreeChange = () => {
  546. if (isFree.value) {
  547. formData.value.fee = "0";
  548. } else {
  549. formData.value.fee = "";
  550. }
  551. };
  552. // ============================
  553. // 이미지 업로드 (기존 + 신규)
  554. // ============================
  555. const imageInput = ref(null);
  556. const image = ref(null); // 신규 업로드 (file + preview)
  557. const existingImagePath = ref(null); // 기존 file_path
  558. const existingImageName = ref(null); // 기존 file_name
  559. const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
  560. const triggerImageInput = () => imageInput.value?.click();
  561. const onImageChange = (e) => {
  562. const file = (e.target.files || [])[0];
  563. e.target.value = "";
  564. if (!file) return;
  565. if (!file.type.startsWith("image/")) {
  566. errorMessage.value = "이미지 파일만 업로드할 수 있습니다.";
  567. return;
  568. }
  569. if (file.size > MAX_IMAGE_SIZE) {
  570. errorMessage.value = "이미지가 5MB를 초과합니다.";
  571. return;
  572. }
  573. if (image.value) URL.revokeObjectURL(image.value.preview);
  574. image.value = { file, preview: URL.createObjectURL(file) };
  575. };
  576. const removeImage = () => {
  577. if (image.value) {
  578. URL.revokeObjectURL(image.value.preview);
  579. image.value = null;
  580. }
  581. };
  582. // ============================
  583. // 라운드/장소 동적 배열
  584. // ============================
  585. let _keySeq = 0;
  586. const nextKey = () => ++_keySeq;
  587. function createPlace() {
  588. return {
  589. _key: nextKey(),
  590. field_id: "",
  591. area_id: "",
  592. partnership_YN: "",
  593. onboards: [], // 적용된 장소 키 배열 (예: 'onboard-1', 'fishing-3')
  594. items: [], // [{ item_id, name, qty }] — Phase 2
  595. // UI 상태
  596. dropdownOpen: false,
  597. searchKeyword: "",
  598. tempSelected: [], // 드롭다운 내 임시 체크 (장소 키 배열)
  599. };
  600. }
  601. function createRound(no) {
  602. return {
  603. _key: nextKey(),
  604. round_no: no,
  605. place_mode: "all",
  606. qualified: "",
  607. items: [], // [{ item_id, name, qty }] — Phase 2
  608. places: [],
  609. };
  610. }
  611. const rounds = ref([createRound(1), createRound(2)]);
  612. function renumberRounds() {
  613. rounds.value.forEach((r, i) => { r.round_no = i + 1; });
  614. }
  615. function addRound() {
  616. if (rounds.value.length >= 5) return;
  617. rounds.value.push(createRound(rounds.value.length + 1));
  618. }
  619. function removeRound(idx) {
  620. if (rounds.value.length <= 2) return;
  621. rounds.value.splice(idx, 1);
  622. renumberRounds();
  623. }
  624. function changePlaceMode(round, mode) {
  625. round.place_mode = mode;
  626. // specific 으로 전환했는데 장소가 없으면 자동으로 장소 1 생성
  627. if (mode === "specific" && round.places.length === 0) {
  628. round.places.push(createPlace());
  629. }
  630. }
  631. function addPlace(round) {
  632. round.places.push(createPlace());
  633. }
  634. function removePlace(round, idx) {
  635. round.places.splice(idx, 1);
  636. // specific 모드인데 장소가 0개면 자동으로 1개 다시 추가 (또는 all 모드로 되돌리기 — 여기선 하나 자동 추가)
  637. if (round.places.length === 0) {
  638. round.places.push(createPlace());
  639. }
  640. }
  641. // ============================
  642. // 장소(선상+낚시터) 검색 드롭다운
  643. // ============================
  644. // 장소 키 헬퍼: 'onboard-1', 'fishing-2' 형태로 고유 식별
  645. const placeKey = (p) => `${p._placeType}-${p.id}`;
  646. const placeByKey = (k) => placesAll.value.find((p) => placeKey(p) === k);
  647. const placeNameByKey = (k) => placeByKey(k)?.name || "?";
  648. const placeTypeByKey = (k) => (k && k.startsWith("fishing-")) ? "fishing" : "onboard";
  649. function closeAllDropdowns() {
  650. rounds.value.forEach((r) =>
  651. r.places.forEach((p) => { p.dropdownOpen = false; })
  652. );
  653. }
  654. function openDropdown(place) {
  655. closeAllDropdowns();
  656. place.tempSelected = [...place.onboards];
  657. place.dropdownOpen = true;
  658. }
  659. function filteredPlaces(place) {
  660. return placesAll.value.filter((p) => {
  661. if (place.field_id && String(p.field_id) !== String(place.field_id)) return false;
  662. if (place.area_id && String(p.area_id) !== String(place.area_id)) return false;
  663. if (place.partnership_YN && p.partnership_YN !== place.partnership_YN) return false;
  664. if (place.searchKeyword) {
  665. const kw = place.searchKeyword.toLowerCase();
  666. if (!String(p.name || "").toLowerCase().includes(kw)) return false;
  667. }
  668. return true;
  669. });
  670. }
  671. function togglePlaceInTemp(place, key) {
  672. const idx = place.tempSelected.indexOf(key);
  673. if (idx === -1) place.tempSelected.push(key);
  674. else place.tempSelected.splice(idx, 1);
  675. }
  676. function isAllFilteredSelected(place) {
  677. const filtered = filteredPlaces(place);
  678. if (filtered.length === 0) return false;
  679. return filtered.every((p) => place.tempSelected.includes(placeKey(p)));
  680. }
  681. function toggleAll(place) {
  682. const filtered = filteredPlaces(place);
  683. const filteredKeys = filtered.map(placeKey);
  684. if (isAllFilteredSelected(place)) {
  685. const set = new Set(filteredKeys);
  686. place.tempSelected = place.tempSelected.filter((k) => !set.has(k));
  687. } else {
  688. const merged = new Set([...place.tempSelected, ...filteredKeys]);
  689. place.tempSelected = [...merged];
  690. }
  691. }
  692. // 지역별 그룹화: [{area, items: [...]}, ...]
  693. function groupedFilteredPlaces(place) {
  694. const filtered = filteredPlaces(place);
  695. const map = new Map();
  696. filtered.forEach((p) => {
  697. const area = p.area_name || "미분류";
  698. if (!map.has(area)) map.set(area, []);
  699. map.get(area).push(p);
  700. });
  701. return Array.from(map.entries()).map(([area, items]) => ({ area, items }));
  702. }
  703. function isAllInGroupSelected(place, items) {
  704. if (!items || items.length === 0) return false;
  705. return items.every((p) => place.tempSelected.includes(placeKey(p)));
  706. }
  707. function toggleAllInGroup(place, items) {
  708. const keys = items.map(placeKey);
  709. if (isAllInGroupSelected(place, items)) {
  710. const set = new Set(keys);
  711. place.tempSelected = place.tempSelected.filter((k) => !set.has(k));
  712. } else {
  713. const merged = new Set([...place.tempSelected, ...keys]);
  714. place.tempSelected = [...merged];
  715. }
  716. }
  717. function applyDropdown(place) {
  718. place.onboards = [...place.tempSelected];
  719. place.dropdownOpen = false;
  720. }
  721. function removePlaceChip(place, key) {
  722. place.onboards = place.onboards.filter((k) => k !== key);
  723. }
  724. // 외부 클릭 시 모든 드롭다운 닫기
  725. function handleDocumentClick() {
  726. closeAllDropdowns();
  727. }
  728. // ============================
  729. // 아이템 선택 모달
  730. // ============================
  731. const itemModal = ref({
  732. isOpen: false,
  733. target: null, // round 또는 place 객체 (둘 다 .items 배열 가짐)
  734. tempSelected: [], // 임시 선택된 item id 배열
  735. searchKeyword: "",
  736. });
  737. function openItemModal(target) {
  738. itemModal.value.target = target;
  739. itemModal.value.tempSelected = target.items.map((i) => i.item_id);
  740. itemModal.value.searchKeyword = "";
  741. itemModal.value.isOpen = true;
  742. }
  743. function closeItemModal() {
  744. itemModal.value.isOpen = false;
  745. itemModal.value.target = null;
  746. itemModal.value.tempSelected = [];
  747. itemModal.value.searchKeyword = "";
  748. }
  749. function toggleItemInModal(itemId) {
  750. const idx = itemModal.value.tempSelected.indexOf(itemId);
  751. if (idx === -1) itemModal.value.tempSelected.push(itemId);
  752. else itemModal.value.tempSelected.splice(idx, 1);
  753. }
  754. function filteredItems() {
  755. if (!itemModal.value.searchKeyword) return itemsAll.value;
  756. const kw = itemModal.value.searchKeyword.toLowerCase();
  757. return itemsAll.value.filter((i) =>
  758. String(i.name || "").toLowerCase().includes(kw)
  759. );
  760. }
  761. function applyItemModal() {
  762. const target = itemModal.value.target;
  763. if (!target) return;
  764. target.items = itemModal.value.tempSelected.map((id) => {
  765. const it = itemsAll.value.find((x) => x.id === id);
  766. return {
  767. item_id: id,
  768. name: it?.name || "?",
  769. type: it?.type || "",
  770. point: it?.point ?? null,
  771. };
  772. });
  773. closeItemModal();
  774. }
  775. // ============================
  776. // 데이터 로드
  777. // ============================
  778. async function loadOptions() {
  779. try {
  780. const [fieldRes, areaRes, onboardRes, fishingRes, itemRes] = await Promise.all([
  781. get("/field/list", { params: { per_page: 1000 } }),
  782. get("/area/list", { params: { per_page: 1000 } }),
  783. get("/onboard/list", { params: { per_page: 1000 } }),
  784. get("/fishing/list", { params: { per_page: 1000 } }),
  785. get("/item/list", { params: { per_page: 1000, status: "Y" } }),
  786. ]);
  787. if (fieldRes.data?.success) fieldOptions.value = (fieldRes.data.data.items || []).reverse();
  788. if (areaRes.data?.success) areaOptions.value = (areaRes.data.data.items || []).reverse();
  789. // 선상 + 낚시터 통합 (_placeType으로 구분)
  790. const onboards = (onboardRes.data?.success ? (onboardRes.data.data.items || []) : [])
  791. .map((o) => ({ ...o, _placeType: "onboard" }));
  792. const fishings = (fishingRes.data?.success ? (fishingRes.data.data.items || []) : [])
  793. .map((f) => ({ ...f, _placeType: "fishing" }));
  794. placesAll.value = [...onboards, ...fishings];
  795. if (itemRes.data?.success) itemsAll.value = itemRes.data.data.items || [];
  796. } catch (e) {
  797. console.error("Load options error:", e);
  798. }
  799. }
  800. // ============================
  801. // 챌린지 로드 + 폼 채우기
  802. // ============================
  803. async function loadChallenge() {
  804. isLoading.value = true;
  805. try {
  806. const { data, error } = await get(`/challenge/${challengeId}`);
  807. if (error || !data?.success) {
  808. errorMessage.value = error?.message || data?.message || "챌린지를 불러올 수 없습니다.";
  809. return;
  810. }
  811. const c = data.data;
  812. // 기본 정보
  813. const feeNum = Number(c.fee);
  814. isFree.value = !isNaN(feeNum) && feeNum === 0;
  815. formData.value = {
  816. name: c.name || "",
  817. fee: String(c.fee ?? ""),
  818. max_participants: c.max_participants || "",
  819. status_YN: c.status_YN || "Y",
  820. description: c.description || "",
  821. };
  822. startDate.value = c.start_date ? String(c.start_date).substring(0, 10) : "";
  823. endDate.value = c.end_date ? String(c.end_date).substring(0, 10) : "";
  824. // 기존 이미지
  825. if (c.file_path) {
  826. existingImagePath.value = c.file_path;
  827. existingImageName.value = c.file_name;
  828. }
  829. // 라운드 변환 (응답 구조 → 폼 구조)
  830. rounds.value = (c.rounds || []).map((r) => {
  831. const round = createRound(r.round_no);
  832. round.place_mode = r.place_mode;
  833. round.qualified = String(r.qualified || "");
  834. if (r.place_mode === "all") {
  835. round.items = (r.items || []).map((it) => ({
  836. item_id: it.item_id,
  837. name: it.name,
  838. type: it.type,
  839. point: it.point,
  840. }));
  841. round.places = [];
  842. } else {
  843. round.items = [];
  844. round.places = (r.places || []).map((p) => {
  845. const place = createPlace();
  846. // field_id, area_id, partnership_YN은 응답에 없음 (필터 조건은 저장 안 됨)
  847. // 사용자가 수정 시 다시 필터 가능
  848. place.onboards = (p.onboards || []).map((o) => `${o.place_type}-${o.place_id}`);
  849. place.items = (p.items || []).map((it) => ({
  850. item_id: it.item_id,
  851. name: it.name,
  852. type: it.type,
  853. point: it.point,
  854. }));
  855. return place;
  856. });
  857. }
  858. return round;
  859. });
  860. // 최소 2라운드 보장 (이상 케이스 대비)
  861. while (rounds.value.length < 2) {
  862. rounds.value.push(createRound(rounds.value.length + 1));
  863. }
  864. } catch (e) {
  865. console.error("[ChallengeEdit] 로드 실패:", e);
  866. errorMessage.value = "서버 오류가 발생했습니다.";
  867. } finally {
  868. isLoading.value = false;
  869. }
  870. }
  871. // 기존 이미지 제거 (즉시 백엔드 호출)
  872. async function removeExistingImage() {
  873. if (!confirm("기존 이미지를 제거하시겠습니까?")) return;
  874. try {
  875. const { data, error } = await del(`/challenge/${challengeId}/image`);
  876. if (error || !data?.success) {
  877. errorMessage.value = error?.message || data?.message || "이미지 제거에 실패했습니다.";
  878. return;
  879. }
  880. existingImagePath.value = null;
  881. existingImageName.value = null;
  882. successMessage.value = "이미지가 제거되었습니다.";
  883. } catch (e) {
  884. console.error("[ChallengeEdit] 이미지 제거 실패:", e);
  885. errorMessage.value = "서버 오류가 발생했습니다.";
  886. }
  887. }
  888. // ============================
  889. // 폼 제출
  890. // ============================
  891. async function handleSubmit() {
  892. errorMessage.value = "";
  893. successMessage.value = "";
  894. // 프론트 1차 검증
  895. if (!formData.value.name.trim()) return (errorMessage.value = "챌린지명을 입력하세요.");
  896. if (!formData.value.fee.toString().trim()) return (errorMessage.value = "참가비를 입력하세요.");
  897. if (!startDate.value) return (errorMessage.value = "시작일을 선택하세요.");
  898. if (!endDate.value) return (errorMessage.value = "종료일을 선택하세요.");
  899. if (!formData.value.max_participants) return (errorMessage.value = "최대 참가자를 입력하세요.");
  900. for (let i = 0; i < rounds.value.length; i++) {
  901. const r = rounds.value[i];
  902. if (!r.qualified) {
  903. return (errorMessage.value = `라운드 ${i + 1}의 진출자 수를 입력하세요.`);
  904. }
  905. if (r.place_mode === "specific") {
  906. if (r.places.length === 0) {
  907. return (errorMessage.value = `라운드 ${i + 1}에 장소를 1개 이상 추가하세요.`);
  908. }
  909. for (let j = 0; j < r.places.length; j++) {
  910. if (r.places[j].onboards.length === 0) {
  911. return (errorMessage.value = `라운드 ${i + 1} 장소 ${j + 1}에 선상을 1개 이상 선택하세요.`);
  912. }
  913. }
  914. }
  915. }
  916. isSaving.value = true;
  917. try {
  918. const payload = {
  919. name: formData.value.name,
  920. fee: formData.value.fee,
  921. start_date: startDate.value,
  922. end_date: endDate.value,
  923. max_participants: Number(formData.value.max_participants),
  924. description: formData.value.description,
  925. status_YN: formData.value.status_YN,
  926. rounds: rounds.value.map((r) => ({
  927. round_no: r.round_no,
  928. place_mode: r.place_mode,
  929. qualified: Number(r.qualified),
  930. items: r.place_mode === "all"
  931. ? r.items.map((it) => ({ item_id: it.item_id }))
  932. : [],
  933. places: r.place_mode === "specific"
  934. ? r.places.map((p) => ({
  935. // 'onboard-1', 'fishing-3' → [{type:'onboard', id:1}, {type:'fishing', id:3}, ...]
  936. onboards: p.onboards.map((key) => {
  937. const i = key.indexOf("-");
  938. return { type: key.substring(0, i), id: Number(key.substring(i + 1)) };
  939. }),
  940. items: p.items.map((it) => ({ item_id: it.item_id })),
  941. }))
  942. : [],
  943. })),
  944. };
  945. const { data, error } = await put(`/challenge/${challengeId}`, payload);
  946. if (error || !data?.success) {
  947. errorMessage.value = error?.message || data?.message || "수정에 실패했습니다.";
  948. return;
  949. }
  950. // 새 이미지가 선택되어 있으면 업로드 (기존 이미지 자동 교체)
  951. if (image.value) {
  952. const fd = new FormData();
  953. fd.append("image", image.value.file);
  954. const { data: imgRes, error: imgErr } = await upload(`/challenge/${challengeId}/image`, fd);
  955. if (imgErr || !imgRes?.success) {
  956. errorMessage.value = "챌린지는 수정됐지만 이미지 업로드에 실패했습니다.";
  957. setTimeout(() => router.push(`/site-manager/challenge/detail/${challengeId}`), 1500);
  958. return;
  959. }
  960. }
  961. successMessage.value = data.message || "챌린지가 수정되었습니다.";
  962. setTimeout(() => {
  963. router.push(`/site-manager/challenge/detail/${challengeId}`);
  964. }, 1000);
  965. } catch (e) {
  966. errorMessage.value = "서버 오류가 발생했습니다.";
  967. console.error("Challenge save error:", e);
  968. } finally {
  969. isSaving.value = false;
  970. }
  971. }
  972. const goToList = () => router.push("/site-manager/challenge/list");
  973. const goToDetail = () => router.push(`/site-manager/challenge/detail/${challengeId}`);
  974. onMounted(async () => {
  975. document.addEventListener("click", handleDocumentClick);
  976. // 옵션 먼저 로드한 후 챌린지 로드 (placesAll 채워야 onboards 매핑 가능)
  977. await loadOptions();
  978. await loadChallenge();
  979. });
  980. onBeforeUnmount(() => {
  981. document.removeEventListener("click", handleDocumentClick);
  982. });
  983. </script>